;
(function(window){
    /**
     * 图片相册，带上传和拖动排序功能
     * @param    {element}  uploadForm        图片上传隐藏表单对象
     * @param    {element}  uploadreturn      图片上传iframe对象
     * @param    {element}  uploadInput       上传按钮对象
     * @param    {element}  savebtn           保存按钮
     * @param    {element}  cancelbtn         取消按钮
     * @param    {element}  imglist           图片列表
     * @param    {string}   tem_html          图片html
     * @param    {string}   url               上传地址
     * @param    {fun}      delectFun         删除图片函数
     * @param    {fun}      saveFun           保存函数
     * @param    {fun}      cancelFun         取消函数


     * @author   hcz
     */
    var uploadImg = function(config){
        this.config = config;
        this.init();
    };
    uploadImg.prototype = {
        init:function(){
            var that = this;
            var config = this.config;

            //图片上传
            config.uploadInput.on('change', function() {
                 if(config.setDisabled){
                   config.setDisabled(); 
                 }
                var input = uploadInput = $(this),
                    list =  config.imglist,
                    files = input.prop('files');

                uploadWrap = input.parents('.btn-wrap');

                if (window.FormData) {

                    if (!files || !files.length) {
                        return;
                    }

                    for (var i = 0, len = files.length; i < len; i++) {
                        that.upload(list, files[i]);
                    }

                    setTimeout(function() {
                        input.prop('value', '');
                        input.prop('files', '');
                    }, 100);
                } else {
                    input.appendTo(config.uploadForm.get(0));
                    config.uploadForm.submit();
                }
            });


            //iframe回调
            config.uploadreturn.on('load', function() {
                var html;
                if (this.contentDocument) {
                    html = $(this.contentDocument.body).text();
                } else if (this.contentWindow.document.documentElement) {
                    html = $(this.contentWindow.document.documentElement).text();
                }

                config.uploadForm.get(0).reset();
                if (!html) {
                    return;
                }

                try {
                    var box = config.imglist
                    data = $.parseJSON(html);

                    if (data.code == 1000) {

                        list.prepend(tplToHtml(config.tem_html,data.content || {}));
                    } else {
                        alert(data.message);
                    }
                } catch (e) {
                    alert('上传图片失败');
                }
            });

            //排序
            var eleDrag = null;

            config.imglist.on("dragstart", ".img", function(ev) {
                eleDrag = ev.target;
            });
            config.imglist.on("dragend", ".img", function(ev) {
                eleDrag = ev.target;
                eleDrag = null;
            });
            config.imglist.on('dragover', '.img', function(ev) {
                ev.preventDefault();
                var t_targrt = $(ev.target);
                if (!t_targrt.hasClass('img')) {
                    t_targrt = t_targrt.parents(".img");
                }
                return true;
            });
            config.imglist.on("drop", ".img", function(ev) {
                ev.preventDefault();
                var t_targrt = $(ev.target);
                if (!t_targrt.hasClass('img')) {
                    t_targrt = t_targrt.parents(".img");
                }
                var index = t_targrt.index() - $(eleDrag).index();
                if (index < 0) {
                    t_targrt.before($(eleDrag));
                } else {
                    t_targrt.after($(eleDrag));
                }
            });


            //保存事件
            if(config.savebtn&&config.saveFun){
                config.savebtn.click(function() {
                    config.saveFun();
                });
            }

            //取消事件
            if(config.cancelbtn&&config.cancelFun){
                config.cancelbtn.click(function() {
                    config.cancelFun();
                });
            }


            //删除操作
            config.imglist.on('click', '.deleteBtn', function() {
                if (confirm('确定删除？')) {
                    if(config.delectFun){
                        config.delectFun($(this));
                    }
                }
            });


        },
        upload:function(list, file){
            var that = this;
            var fd = new FormData();
            fd.append('file', file);

            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                        var data = $.parseJSON(xhr.responseText);
                        if (data.code == 1000) {
                            var tem_html = tplToHtml(that.config.tem_html,data.content || {});
                            list.prepend(tem_html);
                        } else {
                            alert(data.message);
                        }
                    } else {
                        alert(data.message);
                    }
                }
            };

            xhr.open("POST", that.config.url);
            //        xhr.setRequestHeader("X_FILENAME", files[0].name);
            xhr.send(fd);
        }

    }


    function tplToHtml(tpl, datas){
        var items = [],
            datas = Object.prototype.toString.call(datas) === '[object Array]' ? datas : [datas];

        $.each(datas, function(i, data){
            items.push(tpl.replace(new RegExp("[\\{](\\s|\\S)*?[\\}]", "g"), function(prop) {
                var value = data[prop.slice(1,-1)];
                return (typeof value === 'number' && isFinite(value)) ? value : value || '';
            }));
        });

        return items.join('');
    };


    window.uploadImg = uploadImg;
})(window);






